package com.dm.mcode.view;

import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import com.dm.mcode.App;
import com.dm.mcode.Config;
import com.dm.mcode.model.KeyWord;
import com.dm.mcode.model.Msg;
import com.dm.mcode.model.UploadResult;
import com.dm.mcode.network.Network;
import com.dm.mcode.util.DataValidation;
import com.dm.mcode.util.SharedPreferenceUtil;

import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Damon.Han on 2016/10/8 0008.
 */

public class ReadSmsContent extends ContentObserver {
    /**
     * Creates a content observer.
     *
     * @param handler The handler to run {@link #onChange} on, or null if none.
     */
    private MainActivity mActivity;
    private Cursor cursor = null;
    private Msg lastMsg;

    public ReadSmsContent(Handler handler, MainActivity mActivity) {
        super(handler);
        this.mActivity = mActivity;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        Log.e("tag", "onChange");
        readSms();
    }

    /**
     * 读取新收到的短信内容
     */
    private void readSms() {
        // 读取收件箱中指定号码的短信
        String[] columns = new String[]{"_id", "address", "body", "read", "type"};
        String selection = " read=? and type=? ";
        // read是否阅读0未读1已读
        // type-1是接收到的，2是发出的
        String[] args = new String[]{"0", "1"};
        Uri contentUri = Uri.parse("content://sms/inbox");
        cursor = mActivity.managedQuery(contentUri, columns,
                selection, args, "_id desc");
        Msg message = null;
        if (cursor != null && cursor.getCount() > 0) {
            cursor.moveToNext();
            int smsbodyColumn = cursor.getColumnIndex("body");
            int addressColumn = cursor.getColumnIndex("address");
            String smsBody = cursor.getString(smsbodyColumn);
            String address = cursor.getString(addressColumn);
            message = new Msg();
            message.body = smsBody;
            message.address = address;
        }
        parseMsg4Mobile(message);
        if (lastMsg == null) {
            lastMsg = message;
            Msg msg = parseMsg4AuthCode(message);
            uploadMsg(msg);
        } else if (!message.equals(lastMsg)) {
            lastMsg = message;
            Msg msg = parseMsg4AuthCode(message);
            uploadMsg(msg);
        }

        //在用managedQuery的时候，不能主动调用close()方法， 否则在Android 4.0+的系统上会发生崩溃
        if (Build.VERSION.SDK_INT < 14) {
            cursor.close();
        }
    }

    private void parseMsg4Mobile(Msg message) {
        if (message == null) return;
        //验证码手机号:[13155555555]
        String body = message.body;
        String flag = "验证码手机号:";
        if (body.length() > 0 && body.contains(flag)) {
            String mobile = body.replace(flag, "").replace("[", "").replace("]", "");
            if (mobile != null) {
                SharedPreferenceUtil.put(mActivity, Config.SP_MOBILE_PHONE, mobile);
            }
        }
    }

    /**
     * 解析验证码短信
     */
    public Msg parseMsg4AuthCode(Msg message) {
        if (message == null)
            return null;
        String body = message.body;
        List<KeyWord> keyWords = App.getInstance().getList();
        for (int i = 0; i < keyWords.size(); i++) {
            String key = keyWords.get(i).getKEYWORD();
            if (body.contains(key)) {
                message.sort = keyWords.get(i).getSORT();
                return message;
            }
        }
        return null;
    }

    /**
     * 上传验证码
     *
     * @param msg
     */
    private void uploadMsg(Msg msg) {
        if (msg == null) {
            return;
        }
        Log.e("tag", "上传--" + msg.body);
        String s = (String) SharedPreferenceUtil.get(mActivity, Config.SP_MOBILE_PHONE, "");
        if (DataValidation.checkMobile(s)) {
            Network.getCodeApi().uploadMsg(msg.address, msg.body, msg.sort)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<UploadResult>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(UploadResult msg) {
                            Log.d("OK", msg.getMessage() + "");
                        }
                    });
        }
    }

}
